/**
 * @author 木人心
 * @version 1.0.0
 */
import request from '@utils/request'
import { APIResult } from '@utils/request/type'
import { ServerEnum } from '@/api/enum/server'

const uploadFileConfig = {
  headers: { contentType: 'multipart/form-data' },
  transformRequest: [function (data) {
    const form = new FormData()
    form.append('file', data.file)
    return form
  }]
}
/**
 * 上传文件
 * @param params
 */
export const uploadFileAPI = (params: File) => request.post(ServerEnum.File + '/file/upload', { file: params }, uploadFileConfig)

/**
 * 上传文件，成功返回文件 url
 * @param params
 */
export const uploadImageFileAPI = (params: File) => request.post<APIResult<string>>(ServerEnum.File + '/file/upload2', { file: params }, uploadFileConfig)

/**
 * 上传图片，压缩图片
 * @param params
 */
export const uploadImageCompressFileAPI = (params: File) => request.post<APIResult<string>>(ServerEnum.File + '/file/upload-image', { file: params }, uploadFileConfig)

/**
 * 删除图片
 * @param params
 */
export const deleteImageFileAPI = (params: { url: string }) => request.post(ServerEnum.File + '/file/delete', null, { params })

/**
 * 导出|下载文件
 * @param url
 * @param params
 * @param method
 */
export const exportFileAPI = (url: string, params?: any, method: 'get' | 'post' = 'get') => request.request({
  url,
  params,
  method,
  responseType: 'blob',
  transformResponse: [function (data) {
    const url = URL.createObjectURL(data)
    data = {
      url,
      download (fileName: string) {
        const a = document.createElement('a')
        a.href = url
        a.download = fileName
        a.click()
        URL.revokeObjectURL(url)
      }
    }
    return data
  }]
})

/**
 * 导入|上次文件
 * @param url
 * @param params
 */
export const importFileAPI = <R = any>(url: string, params: File) => request.post<R>(url, { file: params }, uploadFileConfig)
